package com.example.demo.untils;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;


@Component
public  class RTSPConverter  implements DisposableBean {
    private static Process ffmpegProcess;
    private static Thread processMonitorThread;
    private static String ffmpegPath = "D:\\jdk18\\ffmpeg-4.3.1-full_build\\bin\\ffmpeg";
    //private static  String outputDir="D:\\jdk18\\hls2\\";

    public static void main(String[] args) {
      //  String outputDir = "D:\\jdk18\\hls2";
     //   startHLSStreaming("rtsp://127.0.0.1:554/easy1.mp4",outputDir);
//        String macAddress = getMACAddress();
//        if (macAddress != null) {
//            System.out.println("MAC Address: " + macAddress);
//        } else {
//            System.out.println("No MAC address found.");
//        }
    }



    ///////////////////
    public int startRTMPStreaming(String rtspUrl, String rtmpUrl) {
        // FFmpeg 命令
        String[] command = {
                ffmpegPath,
                "-i", rtspUrl,
                "-c:v", "copy",
                "-c:a", "aac",
                "-f", "flv",
                rtmpUrl
        };
        return startStreaming(command);
    }

    public static int startHLSStreaming(String rtspUrl,String fileName) {
        // 确保输出目录存在
        String  fileOutputDir="D:\\jdk18\\hls2\\"+fileName;
        File outputDirFile = new File(fileOutputDir);
        if (!outputDirFile.exists()) {
            outputDirFile.mkdirs();
        }
        // FFmpeg 命令
        String[] command = {
                ffmpegPath,
                "-i", rtspUrl,          // 输入 RTSP 流
                "-max_muxing_queue_size", "1024", // # 增加缓冲队列大小
                "-c:v", "libx264",      // 视频流设置为h.264，防止其他格式导致浏览器无法播放
              //  "-an",                  // 禁用音频处理
                "-c:a", "copy",     // 关键！直接复制音频流，不重新编码
                "-f", "hls",            // 输出格式为 HLS
                "-hls_time", "3",      // 每个 TS 文件的时长（秒）
                "-hls_list_size", "10",  // HLS 播放列表中保留的 TS 文件数量
                "-hls_flags", "append_list",
                "-strftime", "1", // 关键！启用时间格式化
                "-hls_segment_filename", fileOutputDir+"\\"+ "%Y%m%d%H%M%S.ts",
                "-hls_flags", "delete_segments", // 自动删除旧的 TS 文件
                fileOutputDir + "\\" + "hlsStream" + ".m3u8",

//                "-rtsp_transport", "tcp",  // 强制使用TCP传输(对于RTSP)
//                "-c:v", "copy",             // 视频流直接复制
//                "-c:a", "copy",             // 音频流直接复制
//                "-f", "mp4",
//                "-y",
//                "D:\\jdk18\\hls2\\test1.mp4"

        };


        return startStreaming(command);
    }



    private static int startStreaming(String[] command) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.inheritIO();

            // 启动FFmpeg进程
            ffmpegProcess = processBuilder.start();

            // 创建监控线程处理进程结束
            processMonitorThread = new Thread(() -> {
                try {
                    ffmpegProcess.waitFor();
                    // 添加日志来记录FFmpeg进程的退出码
                    // log.info("FFmpeg process exited with code: {}",exitCode);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            processMonitorThread.start();
            return 1;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static  int stopStreaming() {
        // if (ffmpegProcess != null && ffmpegProcess.isAlive()) {
        if (ffmpegProcess != null) {
            // 销毁FFmpeg进程
            ffmpegProcess.destroy();
            try {
                // 等待监控线程结束
                if (processMonitorThread != null) {
                    processMonitorThread.join(1000); // 最多等待5秒
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return 0;
            }
        }
        return 200;
    }


    // 关闭应用时关闭FFmpeg
    @Override
    public void destroy() throws Exception {
        if (ffmpegProcess != null) {
            // 销毁FFmpeg进程
            ffmpegProcess.destroy();

            try {
                // 等待监控线程结束
                if (processMonitorThread != null) {
                    processMonitorThread.join(5000); // 最多等待5秒
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}